package com.simple.piger.utils.dingding;

import com.simple.piger.utils.GsonHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author baolw
 * @date 2018/1/16 17:02
 */

public class DingtalkChatbotClient {
    private static RestTemplate template;
    static {
        initTemplate();
    }

    private static void initTemplate() {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(5000);
        httpRequestFactory.setConnectTimeout(5000);
        httpRequestFactory.setReadTimeout(5000);
        template = new RestTemplate();
        template.setRequestFactory(httpRequestFactory);
        template.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    }

    public static SendResult send(String webhook, Message message) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        if (template == null) {
            initTemplate();
        }

        HttpEntity<String> formEntity = new HttpEntity<>(message.toJsonString(), headers);
        String result = template.postForObject(webhook, formEntity, String.class);
        SendResult sendResult = null;
        if (StringUtils.isNotBlank(result)) {
            sendResult = GsonHelper.parseObject(result, SendResult.class);
            sendResult.setIsSuccess(sendResult.getErrcode().equals(Integer.valueOf(0)));
        }
        return sendResult;
    }
}
